package com.asktgapp.user.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.media.midi.MidiDeviceInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroupOverlay;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.application.MyApplication;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.base.BaseFragmentActivity;
import com.asktgapp.base.SearchBaseActivity;
import com.asktgapp.model.MyFollowVO;
import com.asktgapp.model.RentInfoVO;
import com.asktgapp.model.SearchVO;
import com.asktgapp.modulebase.common.adapter.BaseAdapter;
import com.asktgapp.modulebase.common.adapter.BaseViewHolder;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.EngineerDetailActivity;
import com.asktgapp.user.activity.EngineerListActivity;
import com.asktgapp.user.activity.QiuZuDetailActivity;
import com.asktgapp.user.activity.RentDetailActivity;
import com.asktgapp.user.activity.UsedMachineDetailActivity;
import com.asktgapp.utils.ImageDisplayUtil;
import com.asktgapp.widget.RefreshRecyclerView;
import com.asktgapp.widget.SwipeRefreshRecyclerView;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/2/28
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:
 */

public class MyFollowFragment extends BaseFragment {
    private SwipeMenuRecyclerView mRecyclerView;
    private BaseAdapter mBaseAdapter;
    private MyFollowVO myFollowVO;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_my_follow, container, false);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        getBaseActivity().setBackNavigationIcon();
        mRecyclerView = rootView.findViewById(R.id.recycle);
        /**
         * 菜单创建器，在Item要创建菜单的时候调用。
         */
        SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
                int width = getResources().getDimensionPixelSize(R.dimen.view_height_80);

                // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
                // 2. 指定具体的高，比如80;
                // 3. WRAP_CONTENT，自身高度，不推荐;
                int height = ViewGroup.LayoutParams.MATCH_PARENT;
                SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity())
                        .setBackgroundColor(Color.parseColor("#ff5c5d"))
                        .setText("删除")
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);
                swipeRightMenu.addMenuItem(deleteItem);// 添加菜单到右侧。
            }
        };
        ////////////////////////////////////////////////////////////////////////////////

        /**
         * RecyclerView的Item的Menu点击监听。
         */
        SwipeMenuItemClickListener mMenuItemClickListener = new SwipeMenuItemClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge menuBridge) {
                menuBridge.closeMenu();
                int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
                final int adapterPosition = menuBridge.getAdapterPosition(); // RecyclerView的Item的position。
                int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。
                final Object bean = mBaseAdapter.getData().get(adapterPosition);
                if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
                    //0:二手机 1:设备出租 2:设备求租 3:工程师
                    if (bean instanceof MyFollowVO.ProjecterListBean) {
                        MyFollowVO.ProjecterListBean vo = (MyFollowVO.ProjecterListBean) bean;
                        doFollow(3, adapterPosition, vo.getId());
                    } else if (bean instanceof MyFollowVO.LeaseListBean) {
                        MyFollowVO.LeaseListBean vo = (MyFollowVO.LeaseListBean) bean;
                        doFollow(1, adapterPosition, vo.getId());
                    } else if (bean instanceof MyFollowVO.TwoHardListBean) {
                        MyFollowVO.TwoHardListBean vo = (MyFollowVO.TwoHardListBean) bean;
                        doFollow(0, adapterPosition, vo.getId());
                    } else if (bean instanceof MyFollowVO.QiuZuListBean) {
                        MyFollowVO.QiuZuListBean vo = (MyFollowVO.QiuZuListBean) bean;
                        doFollow(2, adapterPosition, vo.getId());
                    }

                } else if (direction == SwipeMenuRecyclerView.LEFT_DIRECTION) {
                }
            }
        };

        mBaseAdapter = new BaseAdapter(getActivity()) {
            @Override
            public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                BaseViewHolder holder = null;
                if (viewType == 3) {//工程师
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_follow_projecter, parent, false),
                            new BaseViewHolder.Callbacks() {
                                @Override
                                public void bind(BaseViewHolder holder, Object data) {

                                    if (data instanceof MyFollowVO.ProjecterListBean) {
                                        MyFollowVO.ProjecterListBean bean = (MyFollowVO.ProjecterListBean) data;
                                        ImageView headImg = holder.getView(R.id.iv_head_engineer);
                                        TextView mTag1 = holder.getView(R.id.tv_tag1);
                                        TextView mTag2 = holder.getView(R.id.tv_tag2);
                                        ImageDisplayUtil.loadCircleHeadImage(getActivity(), headImg, bean.getUserPic());

                                        holder.setText(R.id.tv_price, "¥ " + bean.getAdvisoryPrice() + "元");
                                        if (!TextUtils.isEmpty(bean.getRecommendReason())) {
                                            String[] arr = bean.getRecommendReason().trim().split("##");
                                            String recommend = "";
                                            for (int i = 0; i <arr.length ; i++) {
                                                recommend += "★  "+arr[i]+"\n";
                                            }
                                            holder.setText(R.id.tv_reason,recommend);
                                        }
                                       if(TextUtils.isEmpty(bean.getRealname()))
                                           holder.setText(R.id.tv_name,bean.getUsername());
                                        else
                                           holder.setText(R.id.tv_name,bean.getRealname());
                                        if (Util.isEmpty(bean.getLabel())) {
                                            mTag1.setVisibility(View.GONE);
                                            mTag2.setVisibility(View.GONE);
                                        } else {
                                            String[] str = bean.getLabel().split(",");
                                            if (str.length == 0) {
                                                mTag1.setVisibility(View.GONE);
                                                mTag2.setVisibility(View.GONE);
                                            } else if (str.length == 1) {
                                                if (Util.isEmpty(str[0])) {
                                                    mTag1.setVisibility(View.GONE);
                                                } else {
                                                    mTag1.setVisibility(View.VISIBLE);
                                                }
                                                mTag2.setVisibility(View.GONE);
                                                mTag1.setText(str[0]);
                                            } else if (str.length >= 2) {
                                                mTag1.setVisibility(View.VISIBLE);
                                                mTag2.setVisibility(View.VISIBLE);
                                                mTag1.setText(str[0]);
                                                mTag2.setText(str[1]);
                                            }
                                        }
                                    }
                                }

                                @Override
                                public void onItemClick(View view, int position) {
                                    MyFollowVO.ProjecterListBean bean = (MyFollowVO.ProjecterListBean) mBaseAdapter.getData().get(position);
                                    Intent intent = new Intent(getActivity(), EngineerDetailActivity.class);
                                    intent.putExtra("id", String.valueOf(bean.getId()));
                                    startActivity(intent);
                                }
                            });
                } else if (viewType == 1) {
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_follow_lease, parent, false),
                            new BaseViewHolder.Callbacks() {
                                @Override
                                public void bind(BaseViewHolder holder, Object data) {
                                    if (data instanceof MyFollowVO.LeaseListBean) {
                                        MyFollowVO.LeaseListBean bean = (MyFollowVO.LeaseListBean) data;
                                        ImageView state = holder.getView(R.id.iv_state);
                                        ImageView img = holder.getView(R.id.iv_machine);
                                        holder.setText(R.id.tv_used_machine_name, bean.getTitle());
//                                        DecimalFormat df = new DecimalFormat("0.00");
                                        holder.setText(R.id.tv_price, Utils.D2I(bean.getPrice()) + bean.getPrice_unit());
                                        String pro = bean.getPro_name().replaceAll("省", "");
                                        String city = bean.getCity_name().replaceAll("市", "");
                                        ImageDisplayUtil.LoadNetImageWithUrl(img, getActivity(), bean.getBanner_pic());
//                                        if (pro.equals(city)) {
//                                            holder.setText(R.id.tv_detail, Utils.getDateYMD(bean.getAdd_time())
//                                                    + " | " + pro);
//
//                                        } else {
                                        holder.setText(R.id.tv_detail, Utils.getDateYMD(bean.getAdd_time())
                                                + " | " + pro + " " + city);
//                                        }
                                        //出租0:待售 1:已售 求租没有
                                        state.setVisibility(View.VISIBLE);
                                        if (bean.getState() == 0) {
                                            state.setImageResource(R.mipmap.bg_rent);
                                        } else {
                                            state.setImageResource(R.mipmap.bg_busy);
                                        }
                                    }
                                }

                                @Override
                                public void onItemClick(View view, int position) {
                                    MyFollowVO.LeaseListBean bean = (MyFollowVO.LeaseListBean) mBaseAdapter.getData().get(position);
                                    Intent intent = new Intent(getActivity(), RentDetailActivity.class);
                                    intent.putExtra("id", String.valueOf(bean.getId()));
                                    intent.putExtra("unit", bean.getPrice_unit());
                                    startActivity(intent);
                                }
                            });
                } else if (viewType == 0) {
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_follow_towhard, parent, false),
                            new BaseViewHolder.Callbacks() {
                                @Override
                                public void bind(BaseViewHolder holder, Object data) {
                                    if (data instanceof MyFollowVO.TwoHardListBean) {
                                        MyFollowVO.TwoHardListBean bean = (MyFollowVO.TwoHardListBean) data;
                                        ImageView saleState = holder.getView(R.id.iv_saled);
                                        ImageView img = holder.getView(R.id.iv_machine);
                                        ImageDisplayUtil.LoadNetImageWithUrl(img, getActivity(), bean.getBanner_pic());
                                        holder.setText(R.id.tv_used_machine_name, bean.getTitle());
                                        holder.setText(R.id.detail, Utils.getDateYear(bean.getProduction_date()) +
                                                " | " + Utils.D2I(bean.getWorking_hours()) + "小时 | " + bean.getPro_name().replaceAll("省", "") + bean.getCity_name().replaceAll("市", ""));
                                        DecimalFormat df = new DecimalFormat("0.00");
                                        holder.setText(R.id.tv_price, df.format(bean.getPrice()) + "万元");
                                        if (bean.getState() == 0) {
                                            saleState.setVisibility(View.GONE);
                                        } else {
                                            saleState.setVisibility(View.VISIBLE);
                                        }
                                    }
                                }

                                @Override
                                public void onItemClick(View view, int position) {
                                    MyFollowVO.TwoHardListBean bean = (MyFollowVO.TwoHardListBean) mBaseAdapter.getData().get(position);
                                    Intent intent = new Intent(getActivity(), UsedMachineDetailActivity.class);
                                    intent.putExtra("id", String.valueOf(bean.getId()));
                                    intent.putExtra("unit", "万元");
                                    startActivity(intent);
                                }
                            });

                } else if (viewType == 2) {
                    holder = new BaseViewHolder(LayoutInflater.from(getContext()).inflate(R.layout.item_follow_qiuzhu, parent, false), new BaseViewHolder.Callbacks() {
                        @Override
                        public void bind(BaseViewHolder holder, Object data) {
                            if (data instanceof MyFollowVO.QiuZuListBean) {
                                MyFollowVO.QiuZuListBean bean = (MyFollowVO.QiuZuListBean) data;
                                holder.setText(R.id.tv_qiuzu_title, bean.getTitle());
                                holder.setText(R.id.tv_price, Utils.D2I(bean.getPrice()) + bean.getPrice_unit() + "");
                                String pro = bean.getPro_name().replaceAll("省", "");
                                String city = bean.getCity_name().replaceAll("市", "");
//                                if (pro.equals(city)) {
//                                    holder.setText(R.id.tv_info, Utils.getDateYMD(bean.getAdd_time())
//                                            + " | " + pro + " | "
//                                            + "工期" + bean.getTime_limit() + "天");
//                                } else
                                holder.setText(R.id.tv_info, Utils.getDateYMD(bean.getAdd_time())
                                        + " | " + pro + " "
                                        + city + " | "
                                        + "工期" + bean.getTime_limit() + "天");
                            }

                        }

                        @Override
                        public void onItemClick(View view, int position) {
                            MyFollowVO.QiuZuListBean bean = (MyFollowVO.QiuZuListBean) mBaseAdapter.getData().get(position);
                            Intent intent = new Intent(getActivity(), QiuZuDetailActivity.class);
                            intent.putExtra("id", String.valueOf(bean.getId()));
                            startActivity(intent);
                        }
                    });
                }
                return holder;
            }


            @Override
            public int getItemViewType(int position) {
                Object bean = mBaseAdapter.getData().get(position);
                if (bean instanceof MyFollowVO.TwoHardListBean)
                    return 0;
                if (bean instanceof MyFollowVO.LeaseListBean) {
                    return 1;
                }
                if (bean instanceof MyFollowVO.QiuZuListBean) {
                    return 2;
                }
                if (bean instanceof MyFollowVO.ProjecterListBean) {
                    return 3;
                }
                return 0;
            }
        };
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mRecyclerView.setSwipeMenuCreator(swipeMenuCreator);
        mRecyclerView.setSwipeMenuItemClickListener(mMenuItemClickListener);
        mRecyclerView.setAdapter(mBaseAdapter);
    }

    private void doFollow(int type, final int position, int mId) {
        //取消关注
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        //0:二手机 1:设备出租 2:设备求租 3:工程师
        params.put("type", type);
        params.put("temp", 0);
        params.put("id", mId);
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody> call = apiservice.follow(params);
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                dismissProgress();
                if (response.isSuccessful()) {
                    mBaseAdapter.removeData(position);

                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });
    }


    @Override
    public void loadData() {
        visibleLoading();
        getData();
    }


    public void getData() {
        if(MyApplication.userIdIsEmpty(getContext()))
            return;
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        Call<ApiResponseBody<MyFollowVO>> call = apiservice.myFollow(params);
        call.enqueue(new Callback<ApiResponseBody<MyFollowVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<MyFollowVO>> call, Response<ApiResponseBody<MyFollowVO>> response) {
                inVisibleLoading();
                if (response.isSuccessful()) {
                    myFollowVO = response.body().getResult();
                    setUI(myFollowVO);
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<MyFollowVO>> call, Throwable t) {
                inVisibleLoading();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });
    }

    private void setUI(MyFollowVO bean) {

        List list = new ArrayList();
        if (bean.getProjecterList().size() > 0) {

            list.addAll(bean.getProjecterList());
        }
        if (bean.getLeaseList().size() > 0) {
            list.addAll(bean.getLeaseList());
        }
        if (bean.getTwoHardList().size() > 0) {
            list.addAll(bean.getTwoHardList());
        }
        if (bean.getQiuZuList().size() > 0) {
            list.addAll(bean.getQiuZuList());
        }
        if (list.size() > 0) {
            mBaseAdapter.setData(list);
            inVisibleNoData();
        } else {
            visibleNoData();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
    }
}
